package com.Jee.HttpEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
    private String method;
    private String url;
    private String version;
    private Map<String,String> headers = new HashMap<>();
    private Map<String,String> parameters = new HashMap<>();
    private Map<String,String> cookies = new HashMap<>();
    private String body;

    public static HttpRequest RequestBuilder(InputStream inputStream) throws IOException {
        HttpRequest request = new HttpRequest();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        //1,读取http协议首行
        String firstLine = bufferedReader.readLine();
        String[] firstLineTokens = firstLine.split(" ");
        request.method = firstLineTokens[0];
        request.url = firstLineTokens[1];
        request.version = firstLineTokens[2];
        //2,,读取http url中的参数
        int pos = request.url.indexOf("?");
        if (pos!=-1){
            String parameters = request.url.substring(pos + 1);
            parseKV(parameters,request.parameters);
        }
        //3,解析header
        String line = " ";
        while ((line = bufferedReader.readLine())!=null && line.length()!=0){
            String[] split = line.split(":");
            request.headers.put(split[0],split[1]);
        }
        //4,解析cookie
        String cookie = request.headers.get("Cookie");
        if (cookie!=null){
            parseCookie(cookie,request.cookies);
        }
        //5,解析body

        return request;
    }

    public static void parseCookie(String source,Map<String,String> target){
        String[] splits = source.split("; ");
        for (String kv : splits) {
            String[] split = kv.split("=");
            target.put(split[0],split[1]);
        }
    }

    public static void parseKV(String source,Map<String,String> target){
        String[] splits = source.split("&");
        for (String kv : splits) {
            String[] split = kv.split("=");
            target.put(split[0],split[1]);
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getVersion() {
        return version;
    }

    public String getHeaders(String key) {
        return headers.get(key);
    }

    public String getParameters(String key) {
        return parameters.get(key);
    }

    @Override
    public String toString() {
        return "HttpRequest{" +
                "method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", version='" + version + '\'' +
                ", headers=" + headers +
                ", parameters=" + parameters +
                '}';
    }
}
